package meijuli.com.join51.business.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jhx.common.utils.Constants;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.activity.BaseFragmentActivity;

import com.jhx.common.cache.SimpleCache;
import com.jhx.common.http.ApiManager;
import com.jhx.common.http.HttpRequest;
import com.jhx.common.http.HttpResponse;
import com.jhx.common.http.ResponseCallback;
import meijuli.com.join51.business.model.RecommendObject;
import meijuli.com.join51.business.model.RecommendUser;
import meijuli.com.join51.business.model.TeamCount;
import meijuli.com.join51.business.service.ApiService;
import meijuli.com.join51.business.utils.StringUtil;
import com.jhx.common.utils.ToastUtil;
import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;


/**
 * 我的团队
 *
 * @author Scott Smith  @Date 2016年05月16/5/26日 18:10
 */
public class MyClientFragment extends BaseFragment {
    /**
     * 邀请人头像
     */
    CircleImageView headImageView;
    /**
     * 未添加邀请人Container
     */
    LinearLayout noInviteContainer;
    /**
     * 输入的邀请人手机号码
     */
    EditText inputInviteNumberEditText;
    /**
     * 添加按钮
     */
    Button addInviteBtn;
    /**
     * 已添加邀请人Container
     */
    LinearLayout inviteContainer;
    /**
     * 邀请人名字
     */
    TextView inviteNameTextView;
    /**
     * 用户数量
     */
    TextView clientNumberTextView;

    /**
     * 输入的邀请码
     */
    private String mInviteCode;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my_client, container, false);
        headImageView = view.findViewById(R.id.head_image_view);
        noInviteContainer = view.findViewById(R.id.no_invite_container);
        inputInviteNumberEditText = view.findViewById(R.id.input_invite_number_editText);
        addInviteBtn = view.findViewById(R.id.add_invite_btn);
        inviteContainer = view.findViewById(R.id.invite_container);
        inviteNameTextView = view.findViewById(R.id.invite_name_text_view);
        clientNumberTextView = view.findViewById(R.id.client_number_text_view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mInviteCode = SimpleCache.Companion.get(Constants.RECOMMEND_PHONE);
        BaseFragmentActivity activity = (BaseFragmentActivity) getActivity();
        activity.setToolBarTitle("我的团队");
        getClientInfo();
        inputInviteNumberEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                afterTextChangedByButterKnife(editable);
            }
        });
        headImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onViewClick(view);
            }
        });
        addInviteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onViewClick(view);
            }
        });
    }


    // 获取团队数据
    private void getClientInfo() {
        showLoadingDialog();
        if (!TextUtils.isEmpty(mInviteCode)) {
            requestClientInfo();
        }
        Call<HttpResponse<TeamCount>> call = ApiManager.get().getApiService(ApiService.class)
                .getTeamCount();
        HttpRequest.getRequest().autoRecycle(this).start(call, new ResponseCallback<TeamCount>() {
            @Override
            public void onSuccess(String url, TeamCount data) {
                dismissDialog();
                if (TextUtils.isEmpty(data.getTotalCount())) {
                    clientNumberTextView.setText(0);
                } else {
                    clientNumberTextView.setText(data.getTotalCount());
                }
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                dismissDialog();
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            BaseFragmentActivity activity = (BaseFragmentActivity) getActivity();
            activity.setToolBarTitle("我的团队");
        }
    }

    private void requestClientInfo() {
        Call<HttpResponse<RecommendObject>> call = ApiManager.get()
                .getApiService(ApiService.class).getClientInfo(mInviteCode);
        HttpRequest.getRequest().autoRecycle(this).start(call,
                new ResponseCallback<RecommendObject>() {
                    @Override
                    public void onSuccess(String url, RecommendObject data) {
                        dismissDialog();
                        addRecommend(data);
                    }

                    @Override
                    public void onError(String url, int errorCode, String errorMsg) {
                        super.onError(url, errorCode, errorMsg);
                        dismissDialog();
                    }
                });
    }

    private void addRecommend(RecommendObject result) {
        RecommendUser user = result.getRecommendUser();
        if (user == null) {
            return;
        }
        String cachePhone = SimpleCache.Companion.get(Constants.RECOMMEND_PHONE);
        if (TextUtils.isEmpty(cachePhone)) {
            SimpleCache.Companion.put(Constants.RECOMMEND_PHONE, user.getPhoneNum());
        }
        Glide.with(getContext()).load(user.getHeadImg())
                .error(R.mipmap.default_head)
                .into(headImageView);
        inviteNameTextView.setText(user.getNickName());
        inviteContainer.setVisibility(View.VISIBLE);
        noInviteContainer.setVisibility(View.GONE);
    }

    public void afterTextChangedByButterKnife(Editable s) {
        addInviteBtn.setEnabled(!TextUtils.isEmpty(s.toString()));
    }

    public void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.add_invite_btn:
                mInviteCode = inputInviteNumberEditText.getText().toString();
                if (!StringUtil.isValidatePhoneNumber(mInviteCode)) {
                    ToastUtil.getInstance().showToast(getActivity(), "请输入正确的手机号码");
                    return;
                }
                // 添加推荐人
                addRecommendUser();
                break;
            case R.id.myClientTextView:
                switchFragment(MyClientFragment.this, new MyClientListFragment());
                break;
        }
    }

    private void addRecommendUser() {
        showLoadingDialog();
        Call<HttpResponse<RecommendObject>> call = ApiManager.get().getApiService(ApiService.class)
                .addRecommenderUser(mInviteCode);
        HttpRequest.getRequest().autoRecycle(this).start(call,
                new ResponseCallback<RecommendObject>() {
                    @Override
                    public void onSuccess(String url, RecommendObject data) {
                        dismissDialog();
                        addRecommend(data);
                    }

                    @Override
                    public void onError(String url, int errorCode, String errorMsg) {
                        super.onError(url, errorCode, errorMsg);
                        dismissDialog();
                    }
                });
    }

}
